/**
 * Administrator
 * 2011-3-6
 * TODO
 */
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;
import hc.trip.airticket.httpclient.JsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**
 * @author 0707
 * @date 2011-3-6
 * @description TODO  :经停还没有分析
 */
public class GetFlightListFM {

	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "www.shanghai-air.com");
		    header.put("Referer", "	http://www.shanghai-air.com/NationalB2CWeb/SearchFlight.aspx");
 
		    //将相关查询数据塞入Json
		    JSONObject jsonObject = new JSONObject();
 
		    StringBuffer JsonSB = new StringBuffer();
		    JsonSB.append("{\"TripType\":\"1\",\"SortType\":\"2\",");
		    JsonSB.append("\"FlightSearchStatusList\":[{\"SegNo\":\"0\",\"depCode\":\"").append(queryInfo.getOrgCity()); 
		    JsonSB.append("\",\"arrCode\":\"").append(queryInfo.getDesCity()).append("\",");
		    JsonSB.append("\"depDate\":\"").append(queryInfo.getDateString()).append("\"}],");
		    JsonSB.append("\"PassengerInfoList\":[{\"PaxType\":\"ADT\",\"PaxNumber\":1},{\"PaxType\":\"CHD\",\"PaxNumber\":0},{\"PaxType\":\"INF\",\"PaxNumber\":0}]}");
		     jsonObject = JSONObject.fromObject(JsonSB.toString());   
		    
 
			postData.put("flightsearchstatus", jsonObject);  //0：国内         1：国际、两岸、地区航线
 
 
	        try {
	        	//返回的HTML
				responseText = proxy.doRequest(
		 	    "http://www.shanghai-air.com/NationalB2CWeb/SearchFlight.aspx", postData, header,"UTF-8");
				 resultInfo = (ResultInfo)analyzeResopnseText(responseText);
	  
			}catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
	        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
	
	          	return resultInfo;
			 
		}
		
		
		/**
		 * 根据上海航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      FlightInfo tempInfo = null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象

		      if (source==null||source.trim().length()==0) {
				return null;
			}
		      
		      ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
		      String regexString  = "<input id=\"BusinessCooperation\" type=\"hidden\" value='\\[(.*?)]'\\s*/>";
		      Pattern pattern = Pattern.compile(regexString);
		      Matcher matcher = pattern.matcher(source);
		      String jsonSource ="";                           //JSON表达式
		      if (jsonSource==null||jsonSource.trim().length()>0) {
				 System.out.println("上海航空分析，没有得到正确的JSON");
				 return null;
			}
		      if (matcher.find()) {
		    	  jsonSource = matcher.group(1).trim();
			}
		    Map  map1 =  JsonUtil.getMapFromClientResoponseJsonStr (jsonSource);
		    JSONArray jsonArray =(JSONArray) map1.get("fl");
		    
		     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
		     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
		     boolean tempIsFirstForAll = true;
		    //jsonArray中每一个元素就是一个航班信息
		    for (int i=0 ;i<jsonArray.size();i++) {
		    	tempInfo = new FlightInfo();
				priceList  =  new ArrayList();
		    	Map map2 = null;
		    	map2 = JsonUtil.getMapFromClientResoponseJsonStr (jsonArray.getJSONObject(i));
		    	if (map2==null||map2.size()==0) {
					System.out.println("上海航空分析,没有得到正确的JSON1");
					return null;
				}
		    	String flightNo = (String) map2.get("fn");
		    	tempInfo.setFlightNo(flightNo);
		    	//是否经停
		    
		        int stopOver =  ((Integer)map2.get("sn")).intValue();
		        if (stopOver>0) {
		        	tempInfo.setStopOver(true); 
				}
		        
		    	tempInfo.setPlaneType((String) map2.get("ftc"));
		    	String temp1 =(String) map2.get("dts");  //起飞时间 2011-03-08 08:20:00
		    	String temp2 =(String) map2.get("ats");   //降落时间 2011-03-08 11:50:00
		    	String[] temp11 = temp1.split(" ");
		    	String[] temp22 = temp2.split(" ");
		    	if (temp11.length!=2||temp22.length!=2) {
		    		System.out.println("上海航空分析,起飞降落时间不正确");
					return null;
				} 
		    	//起飞时间、降落时间
		    	tempInfo.setTakeOffTime(temp11[1]);
		    	tempInfo.setArriveTime(temp22[1]);
		    	
		    	//插入是否代码共享 map isc   ;oc::FM  代码共享航空公司
		    	boolean isShareCode =  (Boolean) map2.get("isc");
		    	if (isShareCode) {
                          String shareCodeFlghtNO = (String) map2.get("ofn");
                          tempInfo.setShareCodeFlag(true);
                          tempInfo.setShareCode("代码共享航班，实际承运航班号"+shareCodeFlghtNO);
				}
		    
		    	
		    	
		    	//开始分析价格
		    	JSONArray priceJsonArray = (JSONArray)map2.get("csil");
		    	 double tempMinPrice = 0.0;       //一个航班中所有舱位的最低价格
		    	 double tempMaxPrice = 0.0;       //一个航班中所有舱位的最高价格
		    	 boolean isFirst = true;
		    	for (int j = 0; j < priceJsonArray.size(); j++) {
			        Map priceMap =  null;
			        Map priceMap2 = null;
		    		JSONObject priceJsonObject = priceJsonArray.getJSONObject(j);  //获得每个价格信息的json
		    		priceMap = JsonUtil.getMapFromClientResoponseJsonStr(priceJsonObject);
                   if (priceMap==null||priceMap.size()<=0) {
                	   System.out.println("上海航空分析，没有价格（舱位、价格、remind）信息");
                	   return null;
				}
                   
                   priceInfo = new PriceInfo();
                   priceInfo.setSpace(((String)priceMap.get("c")).toUpperCase());   //一个舱位
					JSONArray priceJsonArray2 = (JSONArray) priceMap.get("fil");     //size=1 里面包含了价格信息和remind
					JSONObject priceJsonObject2 = priceJsonArray2.getJSONObject(0);   //获得价格的jsonobject
					priceMap2 = JsonUtil.getMapFromClientResoponseJsonStr(priceJsonObject2);
					if (priceMap2==null||priceMap2.size()<=0) {
						System.out.println("没有价格（价格、remind）信息");
						return  null;
					}
					double price  =  Double.parseDouble((String)priceMap2.get("p"));   //设置价格
					priceInfo.setPrice(price);          
                     //come on baby  取得reimind
					StringBuffer remindSB = new StringBuffer(); 
					//上海航空根据json返回的相应变量的值来分别输出remind信息：退票、改期、签转
					//退票信息
 
					if ((String)priceMap2.get("rf")!=null&&Float.parseFloat((String)priceMap2.get("rf"))==0) {
						remindSB.append("退票条件：自愿退票收取票面价100%手续费；");
					} 
					else	if ((String)priceMap2.get("ra")!=null&&Float.parseFloat((String)priceMap2.get("ra"))==0) {
						remindSB.append("");
					}
					else	if ((String)priceMap2.get("rap")!=null&&Float.parseFloat((String)priceMap2.get("rap"))==1) {
                        remindSB.append("退票条件：自愿退票收取票面价"+(String)priceMap2.get("ra")+"%手续费；");
					}
					else {
						remindSB.append("退票条件：自愿退票收取￥"+(String)priceMap2.get("ra")+ "手续费；");
					}
					//改期
					if ((String)priceMap2.get("ref")!=null&&Float.parseFloat((String)priceMap2.get("ref"))==0) {
						remindSB.append("改期条件：不允许改期；");
					} 
					else if ((String)priceMap2.get("rea")!=null&&Float.parseFloat((String)priceMap2.get("rea"))==0) {
						remindSB.append("");
					}
					else if ((String)priceMap2.get("reap")!=null&&Float.parseFloat((String)priceMap2.get("reap"))==1) {
						remindSB.append("改期条件：改期收取经济舱全票价"+(String)priceMap2.get("rea")+"%手续费；");
					}
					else{
						remindSB.append("改期条件：改期收取￥"+(String)priceMap2.get("rea")+"手续费；");
					}
					//签转
					if ((String)priceMap2.get("calf")!=null&&Float.parseFloat((String)priceMap2.get("calf"))==0) {
						remindSB.append("签转条件：不得自愿签转。");
					}
					else if ((String)priceMap2.get("cala")!=null&&Float.parseFloat((String)priceMap2.get("cala"))==0) {
						remindSB.append("");
					}
					else if ((String)priceMap2.get("calap")!=null&&Float.parseFloat((String)priceMap2.get("calap"))==1) {
						remindSB.append("签转条件：补齐差额后可签转。");
					}
					else {
						remindSB.append("签转条件：签转收取￥"+(String)priceMap2.get("cala")+"手续费。");
					}
					priceInfo.setRemind(remindSB.toString().trim());
					//remind获取结束
					priceList.add(priceInfo);	
					  //一个航班不同cabin的最低和最高价格获取
			    	  if (isFirst) {
			    		  tempMinPrice = priceInfo.getPrice();
			    		  tempMaxPrice = priceInfo.getPrice();
			    		  tempInfo.setMinprice(tempMinPrice);
			    		  tempInfo.setMaxprice(tempMaxPrice);
			    		  isFirst = false;
					}
			    	 
			    	  //获取同一个航班的不同舱位中的最高和最低价格
					     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = priceInfo.getPrice();
							}
					     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = priceInfo.getPrice(); 
						}
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
		    	}
		    	tempInfo.setPrice(priceList);
			    flightInfos.add(tempInfo);
				   //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   

			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
			     
		    	
			}
 
		    resultInfo.setResultList(flightInfos);	  
			return resultInfo;
		}




}
